package com.atguigu.tingshu.order.context;


import com.atguigu.tingshu.order.interceptor.OrderHandlerInterceptor;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class OrderHandlerInterceptorContext implements ApplicationContextAware {


    // 存储OrderHandlerInterceptor接口的实现类对象
    private static final List<OrderHandlerInterceptor> ORDER_HANDLER_INTERCEPTOR = new ArrayList<OrderHandlerInterceptor>() ;

    public static OrderInfoVo entry(OrderInfoVo orderInfoVo) {
        for( OrderHandlerInterceptor orderHandlerInterceptor : ORDER_HANDLER_INTERCEPTOR){
            orderInfoVo = orderHandlerInterceptor.sbumitOrderRequestProcess(orderInfoVo);
        }
        return orderInfoVo ;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, OrderHandlerInterceptor> beansOfType = applicationContext.getBeansOfType(OrderHandlerInterceptor.class);
        beansOfType.values().stream().sorted((o1,o2) -> o1.sort() - o2.sort()).forEach(orderHandlerInterceptor -> ORDER_HANDLER_INTERCEPTOR.add(orderHandlerInterceptor));
    }
}
